<?php

namespace App\Http\Rest\Admin;

use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Rest\ResourceConverter;
use Framework\Foundation\Rest\RestRequestInfo;
use Psr\Http\Message\ServerRequestInterface;
use Framework\Foundation\Route\RouterHelper;

/**
 * Class AdminRestControl
 * @package App\Http\Rest\Admin
 * @link http://pagination.js.org/  pagenation文档
 *
 * @see  https://www.kuaidi100.com/openapi/api_jump.shtml  查快递
 */
class AdminRestControl
{
    /**
     * @param $params
     * @param ServerRequest $request
     * @return mixed
     */
    public function index(ServerRequestInterface $request)
    {
        /**
         * @var $restRequestInfo RestRequestInfo;
         */
        $restRequestInfo = $request->getAttribute('restRequestInfo');
        $targetInfo = $this->mapResource($restRequestInfo->getRestTargetInfo());

        $className = "\App\Http\Rest\Admin\Resource\\" . $targetInfo['object'];
        if (class_exists($className)) {
            $obj = new $className;
        } else {
            $obj = new DbResource;
        }

        return call_user_func([$obj, $targetInfo['action']], $targetInfo, $request);
    }


    public function mapResource($targetInfo)
    {
        $map = [
            'permission' => 'rbac_permission',
            'role' => 'rbac_role',
            'role_permission' => 'rbac_role_permission',
            'user_role' => 'rbac_user_role',
        ];

        if (isset($map[$targetInfo['resource']])) {
            $targetInfo['resource'] = $map[$targetInfo['resource']];
        }

        return $targetInfo;
    }
}
